package com.mtiiot.fstcpserver.fastdfs.core;
import java.io.IOException;


public class Fastdfs {
	static{
		try {
			ClientGlobal.init();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 上传文件
	 * 
	 * @param filePath
	 * @return 文件存储逻辑key
	 * @throws Exception
	 */
	public static String uploadFile(String filePath) throws Exception {
		Connection conn=new Connection();
		try {
			String uploadResult = conn.getStorageClient1().upload_file1(filePath, null,
					null);
			return uploadResult;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			conn.close();
		}
	}

	/**
	 * 上传文件 by[using byetArray]
	 * @param file_buff
	 * @param fileExtName 文件后缀名
	 * @return
	 * @throws Exception
	 */
	public static String uploadFile(byte[] file_buff, String fileExtName)
			throws Exception {
		Connection conn=new Connection();
		try {
			String uploadResult = conn.getStorageClient1().upload_file1(file_buff,
					fileExtName, null);
			return uploadResult;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			conn.close();
		}
	}

	/**
	 * 下载文件
	 * @param fileKey
	 * @return
	 * @throws java.io.IOException
	 * @throws Exception
	 */
	public static byte[] downLoadFile(String fileKey) throws IOException,
			Exception {
		Connection conn=new Connection();
		try {
			byte[] r=conn.getStorageClient1().download_file1(fileKey);
			return r;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			conn.close();
		}
	}


	/**
	 * 删除文件
	 * 
	 * @param fileKey
	 * @return boolean if true 成功,or失败
	 * @throws Exception
	 */
	public static boolean deleteFile(String fileKey) throws Exception {
		Connection conn=new Connection();
		try {
			int r = conn.getStorageClient1().delete_file1(fileKey);// int. when return 0 ,
															// then deleteFile
															// success ;when
															// return other,then
															// deleteFile
															// failure.
			if (r == 0) {
				return true;
			} else {
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}finally{
			conn.close();
		}
	}

}
